package org.binge.widget.service;

import com.net263.sequence.SequenceFactory;
import org.apache.log4j.Logger;
import org.binge.widget.facade.BpFileService;
import org.binge.widget.facade.model.IBpFile;
import org.binge.widget.service.dataobject.*;
import org.binge.widget.service.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by Kid on 2016/5/8.
 */
@Service("commonBpFileService")
public class BpFileServiceImpl implements BpFileService {

    private static Logger logger = Logger.getLogger(BpFileServiceImpl.class);

    @Autowired
    private BpFileMapper bpFileMapper;
    @Autowired
    private BpDataMapper bpDataMapper;
    @Autowired
    private BpDataLineMapper bpDataLineMapper;
    @Autowired
    private BpDataColMapper bpDataColMapper;

    @Autowired
    private SequenceFactory defaultSequenceFactory;

    @Autowired
    private BpTemplateDataMapper bpTemplateDataMapper;
    @Autowired
    private BpTemplateMapper bpTemplateMapper;


    @Override
    public int insertFileAndData(Map fileMap) throws Exception {
        //文件信息获取
        long fileId = (long) fileMap.get("fileId");
        long dataId = (long) fileMap.get("dataId");
        String originalFileName = (String) fileMap.get("originalFileName");
        String newFileName = (String) fileMap.get("newFileName");
        long opId = (long) fileMap.get("opId");
        long orgId = (long) fileMap.get("orgId");
        String regionId = (String) fileMap.get("regionId");
        String templateCode = (String) fileMap.get("templateCode");
        String statusNotify = (String) fileMap.get("statusNotify");
        String state = (String) fileMap.get("state");
        Integer priority = (int) fileMap.get("priority");
        //BP_FILE表
        BpFile bpFile = new BpFile();
        bpFile.setFileId(fileId);//上传文件唯一标识
        bpFile.setFileName(newFileName);
        bpFile.setTemplateCode(templateCode);
        bpFile.setFileInitSum(0L);
        bpFile.setOpId(opId);
        bpFile.setOrgId(orgId);
        bpFile.setCreateDate(new Date());
        bpFile.setOriginalFileName(originalFileName);
        bpFile.setStatusNotify(statusNotify);
        bpFile.setState(state);
        bpFile.setFileSuccessSum(0L);
        bpFile.setFileErrorSum(0L);
        int lines = bpFileMapper.insertBpFile(bpFile);
        //BP_DATA表
        BpData bpData = new BpData();
        bpData.setDataId(dataId);
        bpData.setFileId(fileId);
        bpData.setPriority(priority);
        bpData.setTemplateCode(templateCode);
        bpData.setDataInitSum(0L);
        bpData.setProcessRegionId(regionId);
        bpData.setProcessOpId(opId);
        bpData.setProcessOrgId(orgId);
        bpData.setCreateDate(new Date());
        bpData.setStatusNotify(statusNotify);
        bpData.setState(state);
        bpData.setDataSuccessSum(0L);
        bpData.setDataErrorSum(0L);
        bpDataMapper.insertBpData(bpData);
        return lines;
    }

    @Override
    public Map<String, Long> insertLineAndCol(List<List<Object>> resultList, Map fileMap, Map<String, Long> lineAndColMap) throws Exception {
        //获取入表附属信息(不能为null,不然数据库报错)
        long opId = (long) fileMap.get("opId");
        long orgId = (long) fileMap.get("orgId");
        String templateCode = (String) fileMap.get("templateCode");
        String state = (String) fileMap.get("state");
        Integer priority = (int) fileMap.get("priority");
        String keyData = (String) fileMap.get("keyData");
        //插入过程信息获取
        long initSum = lineAndColMap.get("initSum");//每次入表的总条数
        long successSum = lineAndColMap.get("successSum");//插入成功数
        long errorSum = lineAndColMap.get("errorSum");//插入失败数
        long fileId = lineAndColMap.get("fileId");
        long dataId = lineAndColMap.get("dataId");
        //入库操作
        try {
            List lineList = new ArrayList();
            for (int j = 0; j < resultList.size(); j++) {
                List rowList = resultList.get(j);
                //BP_DATA_LINE表
                BpDataLine bpDataLine = new BpDataLine();
                Long dataLineId = defaultSequenceFactory.getNextValue("BP_DATA_LINE_SEQ");//主键sequence
                bpDataLine.setDataLineId(dataLineId);
                bpDataLine.setDataId(dataId);
                bpDataLine.setPriority(priority);//优先级设置规则？
                bpDataLine.setLinenum((long) j + 1 + initSum);
                bpDataLine.setKeyData(keyData);
                bpDataLine.setTemplateCode(templateCode);
                bpDataLine.setProcessOpId(opId);
                bpDataLine.setProcessOrgId(orgId);
                bpDataLine.setCreateDate(new Date());
                bpDataLine.setUpdateDate(new Date());
                bpDataLine.setState(state);
                lineList.add(bpDataLine);

                List colList = new ArrayList();
                for (int k = 0; k < rowList.size(); k++) {
                    //BP_DATA_COL表
                    BpDataCol bpDataCol = new BpDataCol();
                    Long dataColId = defaultSequenceFactory.getNextValue("BP_DATA_COL_SEQ");//主键sequence
                    bpDataCol.setDataColId(dataColId);
                    bpDataCol.setDataLineId(dataLineId);
                    bpDataCol.setDataId(dataId);
                    bpDataCol.setColId((long) k);
                    bpDataCol.setColValue((String) rowList.get(k));
                    bpDataCol.setCreateDate(new Date());
                    bpDataCol.setUpdateDate(new Date());
                    bpDataCol.setState(state);
                    colList.add(bpDataCol);
                }
                bpDataColMapper.insertColList(colList);//col批量插入
            }
            bpDataLineMapper.insertLineList(lineList);
            successSum += resultList.size();//成功条数累加
        } catch (Exception e) {
            errorSum += resultList.size();//失败条数累加
            e.printStackTrace();
        }
        initSum += resultList.size();
        //输出值设置
        lineAndColMap.put("fileId", fileId);
        lineAndColMap.put("dataId", dataId);
        lineAndColMap.put("initSum", initSum);
        lineAndColMap.put("successSum", successSum);
        lineAndColMap.put("errorSum", errorSum);
        return lineAndColMap;
    }

    @Override
    public long updateFileAndData(Map fileMap, Map<String, Long> lineAndColMap) throws Exception {
        //入库行列时过程数据(入库file data时需用到)
        long fileId = lineAndColMap.get("fileId");
        long dataId = lineAndColMap.get("dataId");
        long initSum = lineAndColMap.get("initSum");
        long successSum = lineAndColMap.get("successSum");
        long errorSum = lineAndColMap.get("errorSum");
        //BP_FILE表
        BpFile bpFile = new BpFile();
        bpFile.setFileId(fileId);
        bpFile.setFileInitSum(initSum);
        bpFile.setUpdateDate(new Date());
        bpFile.setFileSuccessSum(successSum);
        bpFile.setFileErrorSum(errorSum);
        bpFileMapper.updateBpFile(bpFile);
        //BP_DATA表
        BpData bpData = new BpData();
        bpData.setDataId(dataId);
        bpData.setDataInitSum(initSum);
        bpData.setUpdateDate(new Date());
        bpData.setDataSuccessSum(successSum);
        bpData.setDataErrorSum(errorSum);
        bpDataMapper.updateBpData(bpData);
        return fileId;
    }


    @Override
    public Map selectBpFilesPager(String startDate, String endDate, Integer start, Integer rows) throws Exception {
        Map resultMap = new HashMap();
        List<IBpFile> iBpFileList = new ArrayList<IBpFile>();
        try {
            Integer count = bpFileMapper.selectCount();
            Integer end = start + rows;
            startDate = startDate + " 00:00:00";
            endDate = endDate + " 23:59:59";
            List<BpFile> bpFileList = bpFileMapper.selectBpFilesPager(startDate, endDate, start, end);
            for (int i = 0; i < bpFileList.size(); i++) {
                IBpFile iBpFile = new IBpFile();
                BeanUtils.copyProperties(bpFileList.get(i), iBpFile);
                iBpFileList.add(iBpFile);
            }
            resultMap.put("count", count);
            resultMap.put("iBpFileList", iBpFileList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    @Override
    public int selectSuccessCount(Long fileId) throws Exception {
        int count = -1;
        try {
            BpFile bpFile = bpFileMapper.selectBpFileByFileId(fileId);
            count = bpFile.getFileSuccessSum().intValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }


    @Override
    public List selectBpFileAndDataPager(Integer start, Integer rows, Long fileId) throws Exception {
        List sheetList = new ArrayList();//页面级list，存储行
        try {
            //分页所需数据
            Integer end = start + rows;
            //分页查询行
            List<BpDataLine> bpDataLineList = bpDataLineMapper.selectBpDataLinesByFileId(start, end, fileId);
            for (int i = 0; i < bpDataLineList.size(); i++) {
                List rowList = new ArrayList();//行级list，存储col
                BpDataLine bpDataLine = bpDataLineList.get(i);
                Long bpDataLineId = bpDataLine.getDataLineId();
                if (bpDataLine.getLinenum() != 1L) {
                    List<BpDataCol> bpDataColList = bpDataColMapper.selectBpDataColsByDataLineId(bpDataLineId);
                    for (int j = 0; j < bpDataColList.size(); j++) {
                        BpDataCol bpDataCol = bpDataColList.get(j);
                        Long colId = bpDataCol.getColId();
                        Object colValue = bpDataCol.getColValue();
                        rowList.add(colId.intValue(), colValue);
                    }
                    sheetList.add(rowList);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sheetList;
    }

    @Override
    public List getInitHead(Long fileId) throws Exception {
        List headList = new ArrayList();
        try {
            List bpDataColList = bpDataColMapper.selectBpDataCol_linePager_1(fileId);
            for (int j = 0; j < bpDataColList.size(); j++) {
                BpDataCol bpDataCol = (BpDataCol) bpDataColList.get(j);
                Long colId = bpDataCol.getColId();
                Object colValue = bpDataCol.getColValue();
                headList.add(colId.intValue(), colValue);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return headList;
    }

    @Override
    public List<Map<String, String>> getTableDataPager(int start, int end, long fileId, String templateCode) throws Exception {
        //获得模板相关信息
        List<BpTemplateData> bpTemplateDataList = bpTemplateDataMapper.selectBpTemplateDataList(templateCode);
        //分段调用服务方法(考虑大文件)
        List<BpDataLine> bpDataLineList = null;
        //匹配数据容器
        List resultList = new ArrayList();
        //分段查询获得段入表数据
        bpDataLineList = bpDataLineMapper.selectBpDataLinesByFileId(start, end, fileId);
        //入表数据进行模板匹配
        for (BpDataLine bpDataLine : bpDataLineList) {
            long dataLineId = bpDataLine.getDataLineId();
            List<BpDataCol> bpDataColList = bpDataColMapper.selectBpDataColsByDataLineId(dataLineId);
            // 当查询有值时,进行匹配
            if (bpDataColList.size() > 0) {
                Map<String, String> tableMap = new HashMap();
                for (BpTemplateData bpTemplateData : bpTemplateDataList) {
                    for (BpDataCol bpDataCol : bpDataColList) {
                        if (bpDataCol.getColId() == bpTemplateData.getFileColId()) {
                            tableMap.put(bpTemplateData.getTbColValue(), bpDataCol.getColValue());
                        }
                    }
                }
                resultList.add(tableMap);
            }
        }
        return resultList;
    }

    @Override
    public Map<String, String> getBpTemplateToMap(String templateCode) throws Exception {
        BpTemplate bpTemplate = bpTemplateMapper.selectBpTemplate(templateCode);
        String refUrl = bpTemplate.getRefUrl();
        String refAplName = bpTemplate.getRefAplName();
        String refRefInterface = bpTemplate.getRefInterface();
        Map<String, String> bpTemplateMap = new HashMap();
        bpTemplateMap.put("refUrl", refUrl);
        bpTemplateMap.put("refAplName", refAplName);
        bpTemplateMap.put("refRefInterface", refRefInterface);
        return bpTemplateMap;
    }


}
